package com.jwsoft.manager.core.integration.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.base.common.vo.common.CommonVO;
import com.bifang.module.base.core.helper.DictHelper;
import com.bifang.module.base.core.integration.CommonIntegration;
import com.bifang.module.system.core.dao.model.PersonInfo;
import com.bifang.module.system.core.dao.service.PersonInfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.enums.ComplaintTypeEnum;
import com.jwsoft.manager.common.enums.EduComplaintEnum;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheDetailVO;
import com.jwsoft.manager.common.vo.eduComplaint.EduComplaintKeyVO;
import com.jwsoft.manager.common.vo.eduComplaint.EduComplaintQueryVO;
import com.jwsoft.manager.common.vo.eduComplaint.EduComplaintVO;
import com.jwsoft.manager.core.dao.model.EduComplaint;
import com.jwsoft.manager.core.dao.model.EduStudentEnrollPre;
import com.jwsoft.manager.core.dao.model.EduStudentHouse;
import com.jwsoft.manager.core.dao.service.EduComplaintService;
import com.jwsoft.manager.core.dao.service.EduStudentEnrollPreService;
import com.jwsoft.manager.core.dao.service.EduStudentHouseService;
import com.jwsoft.manager.core.integration.EduComplaintIntegration;
import com.jwsoft.manager.core.integration.OperationCacheIntegration;
import com.jwsoft.manager.core.util.EduEnrollClearCacheHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;
/**
 * 申述管理业务实现类
 *
 * @author wangtao
 * @since 2022-12-02
 */
@ApiService(funcCode = "eduComplaint", title = "申述管理")
public class EduComplaintIntegrationImpl implements EduComplaintIntegration {

    @Autowired
    public EduComplaintService eduComplaintService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private DictHelper dictHelper;
    @Autowired
    private OperationCacheIntegration operationCacheIntegration;
    @Autowired
    private CommonIntegration commonIntegration;

    @Autowired
    EduStudentHouseService eduStudentHouseService;

    @Autowired
    private EduEnrollClearCacheHelper eduEnrollClearCacheHelper;
    @Autowired
    private EduStudentEnrollPreService eduStudentEnrollPreService;

    @Override
    @OpApi(funcCode = "eduComplaint0001", title = "申述管理分页查询", funcType = FuncTypeEnum.query)
    public PageInfo<EduComplaintVO> getList(EduComplaintQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
        List<EduComplaintVO> eduComplaintList;
        if ("1".equals(vo.getType())) {
            //房产使用申诉
            eduComplaintList = eduComplaintService.queryComplaintOneList(vo);
        } else if ("2".equals(vo.getType()) || "3".equals(vo.getType())) {
            //房产信息申诉和房产学区申诉
            eduComplaintList = eduComplaintService.queryComplaintTwoList(vo);
        } else if ("4".equals(vo.getType())||"5".equals(vo.getType())){
            //户籍信息和户籍学区申诉
            eduComplaintList = eduComplaintService.queryComplaintThreeList(vo);
        }else if ("6".equals(vo.getType())){
            //居住证信息申诉
            eduComplaintList = eduComplaintService.queryComplaintFourList(vo);
        }else if ("7".equals(vo.getType())){
            //网签信息申诉
            eduComplaintList = eduComplaintService.queryComplaintFiveList(vo);
        }else if ("8".equals(vo.getType())){
            //社保信息申诉申诉
            eduComplaintList = eduComplaintService.queryComplaintSixList(vo);
        }else if ("9".equals(vo.getType())){
            //企业信息申诉
            eduComplaintList = eduComplaintService.queryComplaintSevenList(vo);
        }else {
            QueryWrapper<EduComplaint> complaintQueryWrapper = new QueryWrapper<>();
            complaintQueryWrapper.lambda().eq(!ObjectUtils.isEmpty(vo.getComplainantId()),EduComplaint::getComplainantId,vo.getComplainantId());
            eduComplaintList = Convert.toList(EduComplaintVO.class,eduComplaintService.list(complaintQueryWrapper));
        }
        if (CollectionUtils.isEmpty(eduComplaintList)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduComplaintVO> pageInfo = new PageInfo<>(eduComplaintList);
        List<Long> personIdList=pageInfo.getList().stream().map(EduComplaintVO::getComplainantId).distinct().collect(Collectors.toList());
        List<PersonInfo> personInfoList=personInfoService.listByIds(personIdList);
        Map<Long,String> idcardMap=new HashMap<>();
        if(!CollectionUtils.isEmpty(personInfoList)){
            idcardMap=personInfoList.stream().collect(Collectors.toMap(PersonInfo::getPersonId, PersonInfo::getIdcard,(k1,k2)->k1));
        }
        for (EduComplaintVO eduComplaintVO : eduComplaintList) {
            if(StringUtils.isBlank(eduComplaintVO.getComplainantIdcard())) {
                eduComplaintVO.setComplainantIdcard(idcardMap.get(eduComplaintVO.getComplainantId()));
            }
        }
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        // 转义数据字典值
        dictHelper.valueToName(eduComplaintList, Arrays.asList(EduComplaintEnum.values()));
        return PagerUtil.parsePagerVo(eduComplaintList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "eduComplaint0002", title = "申述管理根据主键查询详情", funcType = FuncTypeEnum.query)
    public EduComplaintVO getById(EduComplaintKeyVO vo) {
        EduComplaint entity = eduComplaintService.getById(vo.getComplaintId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        EduComplaintVO result = Convert.convert(EduComplaintVO.class, entity);
        PersonInfo personInfo = personInfoService.getById(result.getComplainantId());
        if (!ObjectUtils.isEmpty(personInfo)){
            result.setComplainantIdcard(personInfo.getIdcard());
        }
        return result;
    }
    /** 保存前统一校验*/
    @Override
    @OpApi(funcCode = "eduComplaint0003", title = "申述管理保存前校验", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduComplaintVO vo) {

        if (ObjectUtils.isEmpty(vo.getComplaintId())) {
            if(StringUtils.isBlank(vo.getAreaCode())){
                //获取当前部署行政区划
                CommonVO commonVO=new CommonVO();
                commonVO.setParamKey("area_code");
                String areaCode=commonIntegration.getValueByKey(commonVO);
                if(StringUtils.isBlank(areaCode)){
                    throw new AppException("系统参数中当前部署行政区划不能为空");
                }
                vo.setAreaCode(areaCode);
            }
            EduOperationCacheDetailVO eduOperationCacheDetailVO=operationCacheIntegration.getPeriodYear();
            Integer year=eduOperationCacheDetailVO.getYear();
            vo.setYear(year);
            QueryWrapper<EduComplaint> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(EduComplaint::getType, vo.getType())
                    .eq(EduComplaint::getYear,year)
                    .eq(EduComplaint::getAreaCode,vo.getAreaCode())
                    .eq(EduComplaint::getHandleStatus, BoolEnum.FALSE.getType());
            queryWrapper.lambda().eq(EduComplaint::getComplainantId, SessionUtil.getSessionInfo().getPersonId());
            Long count = eduComplaintService.count(queryWrapper);
            if (count > 0) {
                throw new AppException(1001,"该申诉类型已申诉但未处理，请耐心等待管理员处理");
            }
            if(StringUtils.isNotBlank(vo.getOtherId())){
                QueryWrapper<EduComplaint> queryCountWrapper=new QueryWrapper<>();
                queryCountWrapper.lambda().eq(EduComplaint::getType,vo.getType())
                        .ne(EduComplaint::getHandleStatus, BoolEnum.FALSE.getType())
                        .eq(EduComplaint::getYear,year)
                        .eq(EduComplaint::getAreaCode,vo.getAreaCode())
                        .eq(EduComplaint::getOtherId,vo.getOtherId());
                queryCountWrapper.lambda().eq(EduComplaint::getComplainantId,SessionUtil.getSessionInfo().getPersonId());
                if(eduComplaintService.count(queryCountWrapper)>=3){
                    throw new AppException("该类型的申诉您的申诉已超过3次，不能再次申诉，请到我的申诉查看申诉结果");
                }
            }else{
                QueryWrapper<EduComplaint> queryCountWrapper=new QueryWrapper<>();
                queryCountWrapper.lambda().eq(EduComplaint::getType,vo.getType())
                        .ne(EduComplaint::getHandleStatus, BoolEnum.FALSE.getType())
                        .eq(EduComplaint::getYear,year)
                        .eq(EduComplaint::getAreaCode,vo.getAreaCode())
                        .isNull(EduComplaint::getOtherId);
                queryCountWrapper.lambda().eq(EduComplaint::getComplainantId,SessionUtil.getSessionInfo().getPersonId());
                if(eduComplaintService.count(queryCountWrapper)>=3){
                    throw new AppException("该类型的申诉您已超过3次，不能再次申诉，请到我的申诉查看申诉结果");
                }
            }

        }
        //主键不为空为修改校验
    }

    @Override
    @OpApi(funcCode = "eduComplaint0004", title = "申述管理新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "eduComplaint0004",
            operationName = "申述管理新增",
            dataType = "complaintId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduComplaintVO add(EduComplaintVO vo) {
        //保存前校验
        checkSave(vo);
        vo.setComplainantId(SessionUtil.getSessionInfo().getPersonId());
        vo.setHandleStatus("0");
        //保存数据
        EduComplaint entity = Convert.convert(EduComplaint.class, vo);
        eduComplaintService.save(entity);
        //将主键设置回vo使操作日志可以取到
        vo.setComplaintId(entity.getComplaintId());
        clearCache(entity);
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduComplaint0005", title = "申述管理修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduComplaint0005",
            operationName = "申述管理修改",
            dataType = "complaintId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduComplaintVO edit(EduComplaintVO vo) {
        if (ObjectUtils.isEmpty(vo.getComplaintId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        EduComplaint oldEntity = eduComplaintService.getById(vo.getComplaintId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        EduComplaint entity = Convert.convert(EduComplaint.class, vo);
        eduComplaintService.updateById(entity);
        clearCache(entity);
        return vo;
    }
    //清除缓存
    private void clearCache(EduComplaint entity){
        //查询人员
        if(entity==null||entity.getComplainantId()==null){
            return;
        }
        QueryWrapper<EduStudentEnrollPre> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().select(EduStudentEnrollPre::getStudentEnrollPreId,EduStudentEnrollPre::getIdcard,EduStudentEnrollPre::getFatherIdcard,EduStudentEnrollPre::getMotherIdcard)
                .eq(EduStudentEnrollPre::getYear,entity.getYear())
                .and( wrapper -> {
                    wrapper.eq(EduStudentEnrollPre::getPersonId, entity.getComplainantId())
                            .or()
                            .eq(EduStudentEnrollPre::getFatherId, entity.getComplainantId())
                            .or()
                            .eq(EduStudentEnrollPre::getMotherId, entity.getComplainantId());
                });
        List<EduStudentEnrollPre> list=eduStudentEnrollPreService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)){
            return;
        }
        for (EduStudentEnrollPre pre:list) {
            if (ComplaintTypeEnum.fc.getType().equalsIgnoreCase(entity.getType()) || ComplaintTypeEnum.fcxq.getType().equalsIgnoreCase(entity.getType()) || ComplaintTypeEnum.fcsy.getType().equalsIgnoreCase(entity.getType())) {
                //房产
                eduEnrollClearCacheHelper.clearCacheMyEnrollPreFc(pre.getFatherIdcard());
                eduEnrollClearCacheHelper.clearCacheMyEnrollPreFc(pre.getMotherIdcard());
                eduEnrollClearCacheHelper.clearCacheMyEnrollPreFc(pre.getIdcard());
            } else if (ComplaintTypeEnum.hj.getType().equalsIgnoreCase(entity.getType()) || ComplaintTypeEnum.hjxq.getType().equalsIgnoreCase(entity.getType())) {
                //户籍
                eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getFatherIdcard());
                eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getMotherIdcard());
                eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getIdcard());
            } else if (ComplaintTypeEnum.sb.getType().equalsIgnoreCase(entity.getType())) {
                //社保
                eduEnrollClearCacheHelper.clearCacheMyEnrollPreSb(pre.getFatherIdcard());
                eduEnrollClearCacheHelper.clearCacheMyEnrollPreSb(pre.getMotherIdcard());
                eduEnrollClearCacheHelper.clearCacheMyEnrollPreSb(pre.getIdcard());
            } else if (ComplaintTypeEnum.wq.getType().equalsIgnoreCase(entity.getType())) {
                //网签
                eduEnrollClearCacheHelper.clearCacheMyEnrollPreWq(pre.getFatherIdcard());
                eduEnrollClearCacheHelper.clearCacheMyEnrollPreWq(pre.getMotherIdcard());
                eduEnrollClearCacheHelper.clearCacheMyEnrollPreWq(pre.getIdcard());
            } else if (ComplaintTypeEnum.jzz.getType().equalsIgnoreCase(entity.getType())) {
                //居住证
                eduEnrollClearCacheHelper.clearCacheMyEnrollPreJzz(pre.getFatherIdcard());
                eduEnrollClearCacheHelper.clearCacheMyEnrollPreJzz(pre.getMotherIdcard());
                eduEnrollClearCacheHelper.clearCacheMyEnrollPreJzz(pre.getIdcard());
            } else if (ComplaintTypeEnum.qy.getType().equalsIgnoreCase(entity.getType())) {
                //企业
                eduEnrollClearCacheHelper.clearCacheMyEnrollPreQy(pre.getFatherIdcard());
                eduEnrollClearCacheHelper.clearCacheMyEnrollPreQy(pre.getMotherIdcard());
                eduEnrollClearCacheHelper.clearCacheMyEnrollPreQy(pre.getIdcard());
            }
            eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getFatherIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getMotherIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getIdcard());
            eduEnrollClearCacheHelper.clearCachePreBefore(pre.getStudentEnrollPreId());
        }
    }
    @Override
    @OpApi(funcCode = "eduComplaint0006", title = "申述管理根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "eduComplaint0006",
            operationName = "申述管理删除",
            dataType = "complaintId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduComplaintKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getComplaintId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduComplaint entity = eduComplaintService.getById(vo.getComplaintId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        eduComplaintService.removeById(vo.getComplaintId());
        clearCache(entity);
    }

    @Override
    @OpApi(funcCode = "eduComplaint0007", title = "处理投诉反馈", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "eduComplaint0007",
            operationName = "处理投诉反馈",
            dataType = "complaintId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void handleComplainant(EduComplaintVO vo) {
        Assert.hasText(vo.getComplaintId(), "处理失败，查询不到申述主键！");
        EduComplaint eduComplaint = eduComplaintService.getById(vo.getComplaintId());
        eduComplaint.setHandlerId(SessionUtil.getSessionInfo().getUserId());
        eduComplaint.setHandleTime(new Date());
        eduComplaint.setHandlerName(SessionUtil.getSessionInfo().getFullName());
        BeanUtil.copyProperties(vo, eduComplaint, CopyOptions.create().ignoreNullValue());
        String studentHouseId = vo.getOtherId();
        if ("1".equals(vo.getType())) {
            if ("1".equals(vo.getHandleStatus())) {
                EduStudentHouse studentHouse = eduStudentHouseService.getById(studentHouseId);
                if(studentHouse!=null){
                    studentHouse.setStatus("9");
                    eduStudentHouseService.updateById(studentHouse);
                }

            }
        }
        eduComplaintService.updateById(eduComplaint);
        clearCache(eduComplaint);
    }

}
